import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import GpNavbar from "@/components/GpNavbar";
import GpProtected from "@/components/GpProtected";
import { GpTouchableView } from "@/components/GpTouchableView";
import { pageMapper } from "@/constants/pageMap";
import { NAVIGATION_BASE_LAYOUT } from "@/hooks/useLayout";
import { useNavigationOpacity } from "@/hooks/useNavigationOpacity";
import { navigate } from "@/utils/navigation";
import { Image, Navigator, Text, View } from "@tarojs/components";
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import styles from "./index.module.css";
import { useAuthStore } from "@/store";
import { useImmer } from "use-immer";
import { postHomejoblist } from "@/apis/endpoint/home";
import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from "@tarojs/taro";
import { HomeJobListResult } from "@/apis/endpoint/model";
import { getSalaryText } from "@/utils/app";

enum FilterType {
  ALL,
  LATEST,
  NEARBY
}
export default function Index() {
  const authenticated = useAuthStore(state => state.userInfo?.memberId)
  const memberProfile = useAuthStore(state => state.memberProfile)
  const [navigationHeight, setNavigationHeight] = useState(NAVIGATION_BASE_LAYOUT.navigationHeight + NAVIGATION_BASE_LAYOUT.statusBarHeight)
  const [opacity] = useNavigationOpacity()
  const [filter, setFilter] = useState(FilterType.ALL)
  const filterOptions: IOption<FilterType>[] = [
    {value: FilterType.ALL, label: '全部'},
    {value: FilterType.LATEST,label: '最新'},
    {value: FilterType.NEARBY,label: '附近'}
  ]
  const searchRef = useRef({
    hasNext: true,
    pageIndex: 1,
    filter
  })
  const [jobList, setJobList] = useImmer<HomeJobListResult[]>([])
  useEffect(() => {
    fetchJobList(true)
  }, [memberProfile])
  useDidShow(() => {
    if (authenticated && searchRef.current.pageIndex === 1 && jobList.length !== 0) {
      fetchJobList()
    }
  })
  usePullDownRefresh(() => {
    Taro.startPullDownRefresh()
    fetchJobList(true)
    .finally(() => {
      Taro.stopPullDownRefresh()
    })
  })
  useReachBottom(() => {
    if (authenticated && searchRef.current.hasNext) {
      searchRef.current.pageIndex++
      fetchJobList()
    }
  })
  function authFulfilledFn() {
    return fetchJobList(true)
  }
  async function fetchJobList(refresh = false) {
    if (refresh) searchRef.current.pageIndex = 1
    const field = searchRef.current.filter === FilterType.LATEST ? "createTime"
                : searchRef.current.filter === FilterType.NEARBY ? "distance"
                : void 0
    const { items, count } = await postHomejoblist({
      page: {
        pageIndex: searchRef.current.pageIndex,
        pageSize: 10
      },
      search: {
        cityId: memberProfile?.cityId,
        jobTypeId: memberProfile?.jobTypeId
      },
      sort: {
        reverse: true,
        field
      }
    }).send()
    const nextList = searchRef.current.pageIndex === 1 ? items: jobList.concat(items)
    setJobList(nextList)
    searchRef.current.hasNext = count > nextList.length
  }
  function handleJobTap(job: HomeJobListResult) {
    navigate(pageMapper.position.job, {id: job.id})
  }
  function renderLeftExtra() {
    return (
      <View className="flex flex-row gap-[32px]">
        {
          !authenticated || memberProfile?.jobTypeName
          ? (
          <View className="flex flex-col items-center gap-[8px]">
            <Text className="text-primary text-[36px] leading-[36px] font-bold whitespace-nowrap">
              {authenticated ? memberProfile?.jobTypeName : "登录查看更多"}
            </Text>
            <Image src="/static/images/position/checked-icon.png" className="w-[44px] h-[20px] object-cover" />
          </View>
          ) : null
        }
        <GpProtected>
          <Navigator url={`/${pageMapper.robot.setting}`} hoverClass="none">
            <GpFontIcon name="icon-tianjia" size={32} color="#707275" />
          </Navigator>
        </GpProtected>
      </View>
    )
  }
  function renderSettingCard() {
    return (
      <View className="pt-[12px] px-[16px] box-border">
        <View className="bg-white/80 rounded-[24px] h-[232px] border-[2px] border-solid border-white backdrop-blur-[20px] relative pt-[32px] pl-[40px]">
          <Image src="/static/images/position/xiaozhi-bg.png" className="w-[292px] h-[232px] object-cover absolute top-0 right-0 bottom-0" />
          <View className="text-[32px] font-bold leading-[32px] text-transparent inline-block" style={{
            backgroundImage: `linear-gradient(90deg, #0095FF 0%, #1640EE 31.94%, #A454FA 76.78%, #FA5470 100%)`,
            "-webkit-background-clip": "text"
          }}>
            我是小智，您的求职小助理!
          </View>
          <View className="text-secondary text-[24px] leading-[24px] mt-[20px]">我可以帮助你自动沟通求职哦！</View>
          <GpProtected>
            <View className="relative mt-[28px] w-[280px] h-[64px] box-border rounded-[16px] overflow-hidden">
              <Image src="/static/images/robot/button-bg.png" className="absolute inset-0 object-cover w-full h-full" />
              <GpTouchableView className="relative w-full h-full box-border flex flex-row justify-center items-center text-white text-[24px] font-bold" onClick={() => {
                navigate(pageMapper.robot.setting)
              }}>
                一键开启  AI找工作
              </GpTouchableView>
            </View>
          </GpProtected>
        </View>
      </View>
    )
  }
  function renderList() {
    return (
      <View className={clsx("pt-[12px] box-border", {
        "pb-[244px]": !authenticated
      })}>
        <View className="flex flex-row items-center h-[80px]">
          {
            filterOptions.map(item => (
              <GpTouchableView key={item.value}
                onClick={() => {
                  if (filter === item.value) return
                  setFilter(item.value)
                  searchRef.current.filter = item.value
                  fetchJobList(true)
                }}
                className={clsx("px-[32px] h-full text-[28px] leading-[80px]", filter === item.value ? "text-theme font-bold" : "text-placeholder")}
              >
                {item.label}
              </GpTouchableView>
            ))
          }
        </View>
        <View className="pt-[16px] px-[16px] box-border">
          {
            jobList.map((item, index) => (
              <View key={item.id} className="relative pb-[16px]">
                <View className={clsx("box-border h-[304px] px-[24px] flex flex-col justify-center rounded-[24px] bg-white", {
                  [styles.lastItem]: index === jobList.length - 1 && !authenticated
                })} onClick={() => handleJobTap(item)}>
                  <View className="flex flex-row gap-[24px]">
                    <Text className="truncate flex-1 w-0 text-primary text-[36px] leading-[36px] font-bold">{item.name}</Text>
                    <Text className="flex-none text-[32px] leading-[32px] font-bold text-theme">{getSalaryText(item)}{item.salaryCount ? `·${item.salaryCount}薪` : null}</Text>
                  </View>
                  <View className="flex flex-row items-center text-[28px] leading-[28px] text-secondary gap-[40px] mt-[28px]">
                    <View className="max-w-[304px] truncate">{item.companyName}</View>
                    <View>{item.companyIndustryName}</View>
                    <View>{item.companyScale}</View>
                  </View>
                  <View className="flex flex-row flex-nowrap gap-[8px] items-center mt-[20px]">
                    <View className="h-[48px] leading-[48px] px-[16px] bg-[#F4F6FC] rounded-[8px] text-[26px] text-secondary">
                      {item.experienceDisplay}
                    </View>
                    <View className="h-[48px] leading-[48px] px-[16px] bg-[#F4F6FC] rounded-[8px] text-[26px] text-secondary">
                      {item.educationDisplay}
                    </View>
                    <View className="h-[48px] leading-[48px] px-[16px] bg-[#F4F6FC] rounded-[8px] text-[26px] text-secondary">
                      {item.workModeJson?.name}
                    </View>
                    <View className="h-[48px] leading-[48px] px-[16px] bg-[#F4F6FC] rounded-[8px] text-[26px] text-secondary">
                      {item.jobTypeName}
                    </View>
                  </View>
                  <View className="flex flex-row items-center gap-[16px] mt-[24px]">
                    <View className="rounded-[50%] overflow-hidden size-[40px] flex-none">
                      <Image src={item.publishUserAvatar ?? __DEF_AVATAR__} className="size-full object-conver" />
                    </View>
                    <View className="flex-1 w-0 box-border text-primary leading-[24px] text-[24px]">
                      {item.publishUserName} · HR
                    </View>
                    <View className="flex-none text-third leading-[24px] text-[24px]">
                      {item.jobAddress?.regionName} · {item.jobAddress?.address}·距你{item.distance}km
                    </View>
                  </View>
                </View>
                {
                  index === jobList.length - 1 && !authenticated
                  ? (
                  <GpProtected authFulfilledFn={authFulfilledFn} className="left-0 right-0 bottom-0 !absolute">
                    <View className="w-[686px] h-[96px] rounded-[64px] bg-theme flex flex-row justify-center items-center text-white text-[32px] mx-auto">
                      登录查看更多职位
                    </View>
                  </GpProtected>
                  ) : null
                }
              </View>
            ))
          }
        </View>
      </View>
    )
  }
  function renderLoginTip() {
    if (authenticated) return null
    return (
      <View className="px-[16px] fixed bottom-[20px] left-0 right-0 box-border">
        <View className="bg-black/80 rounded-[24px] h-[112px] box-border flex flex-row items-center px-[24px] gap-[12px]">
          <Image src="/static/images/position/magic.png" className="size-[48px] object-cover flex-none" />
          <Text className="text-white text-[28px] font-medium flex-1 w-0">AI帮你极速找工作，快来体验吧</Text>
          <GpProtected authFulfilledFn={authFulfilledFn} className="flex-none">
            <View className="flex-none flex flex-row justify-center items-center text-white text-[24px] rounded-[24px] font-medium h-[48px] px-[20px] bg-linear-90 from-0% from-[#00BBFF] to-100% to-theme">
              登录体验
            </View>
          </GpProtected>
        </View>
      </View>
    )
  }
  return <GpContainer className="bg-[#F4F6FC]">
    <GpNavbar
      navigationBarBackgroundColor={`rgba(255, 255, 255, ${opacity})`}
      navigationBarPlaceholder={false}
      navigationBarTitleText={null}
      renderLeftExtra={renderLeftExtra}
      onLayout={({statusBarHeight, navigationHeight}) => setNavigationHeight(statusBarHeight + navigationHeight)}
    />
    <View className="fixed left-0 right-0 top-0 z-0">
      <Image src="/static/images/common/home-bg.png" className="w-[750px] h-[400px] object-cover" />
    </View>
    <View className="relative z-10" style={{
      paddingTop: `${navigationHeight}px`
    }}>
      {renderSettingCard()}
      {renderList()}
      {renderLoginTip()}
    </View>
  </GpContainer>
}
